package mvp;

import java.lang.ref.SoftReference;
import java.lang.ref.WeakReference;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

/**
 * @author:ike
 * @function: presenter代理基类
 * @creat time:14:30 2017/12/11
 **/

public abstract class BasePresenter<V extends IBaseView> {
    /**
     * 原始的View
     */
    private SoftReference<V> mView;
    /**
     * 动态代理view层的对象
     */
    protected V proxyView;


    /**
     * 绑定view：动态代理
     *
     * @param view
     */
    public void attachView(V view) {
        this.mView = new SoftReference<V>(view);
        proxyView = (V) Proxy.newProxyInstance(view.getClass().getClassLoader(),
                mView.getClass().getInterfaces(),
                new InvocationHandler() {
                    @Override
                    public Object invoke(Object o, Method method, Object[] objects) throws Throwable {
                        if (mView != null && mView.get() != null) {
                            return method.invoke(mView, objects);
                        }
                        return null;
                    }
                });

    }

    /**
     * 解绑view
     */
    public void deAttachView() {
        this.proxyView = null;
        this.mView = null;
    }


}
